package com.thinkit.bigdata.web.controller.bus;

import com.google.common.base.Strings;
import com.thinkit.bigdata.core.feature.orm.mybatis.Page;
import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.core.util.excel.XlsUtil;
import com.thinkit.bigdata.web.model.BaseEntity;
import com.thinkit.bigdata.web.model.bus.BusWorkExample;
import com.thinkit.bigdata.web.model.bus.BusWorkModelExample;
import com.thinkit.bigdata.web.model.bus.BusWorkWithBLOBs;
import com.thinkit.bigdata.web.model.config.SysArea;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.service.bus.BusWorkModelService;
import com.thinkit.bigdata.web.service.bus.BusWorkService;
import com.thinkit.bigdata.web.service.config.AreaService;
import com.thinkit.bigdata.web.service.sec.UserService;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 质检任务
 * Created by hccl on 2018/9/26.
 */
@RestController
@RequestMapping("/per-task")
public class PerTask {

    private static Logger logger = Logger.getLogger(PerTask.class);

    @Resource
    private BusWorkService busWorkService;

    @Resource
    private BusWorkModelService busWorkModelService;

    @Resource
    private AreaService areaService;

    @Resource
    private UserService userService;

    @Resource
    private ESUtil esUtil;

    @RequestMapping(value = "/get-data-list", method = RequestMethod.POST)
    public HtmlResult getPerTaskData(HttpServletRequest request) {
        String logTxt = "【质检任务分页查询】";
        logger.info(logTxt);
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));//起始页
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));//每页条数
        logger.info(logTxt + "pageNum = " + pageNum);
        logger.info(logTxt + "pageSize = " + pageSize);
        Page page = new Page<>(pageNum + 1, pageSize);
        Map<String,Object> map = getDataQuery(request, logTxt);
        return HtmlResult.success(busWorkService.selectWorkInfos(page, map), page.getTotalCount());
    }

    private Map<String,Object> getDataQuery(HttpServletRequest request, String logTxt) {
        String provinceCodes = request.getParameter("provinceCode");//省份标识
        String workId = request.getParameter("workId");//任务名称
        String scoreFlag = request.getParameter("scoreFlag");//任务名称
        String evalCycleStart = request.getParameter("evalCycleStart");//考核周期开始
        String evalCycleEnd = request.getParameter("evalCycleEnd");//考核周期截止
        String createTimeBegin = request.getParameter("createTimeBegin");//创建时间
        String createTimeEnd = request.getParameter("createTimeEnd");//创建时间
        String proStatus = request.getParameter("proStatus");//处理状态
        String createUserId = request.getParameter("createUserId");//创建人
        String modelIds = request.getParameter("modelId");//创建人
        String workType = request.getParameter("workType");//创建人
        String onsetTimeBegin = request.getParameter("onsetTimeBegin");//发布时间
        String onsetTimeEnd = request.getParameter("onsetTimeEnd");//发布时间
        String callStartTime = request.getParameter("callStartTime");//通话开始时间
        String callEndTime = request.getParameter("callEndTime");//通话结束时间
        String sortName = request.getParameter("sortName");//排序字段
        String sortOrder = request.getParameter("sortOrder");//排除方式
        logger.info(logTxt + "sortName = " + sortName);
        logger.info(logTxt + "sortOrder = " + sortOrder);
        logger.info(logTxt + "evalCycleStart = " + evalCycleStart);
        logger.info(logTxt + "evalCycleEnd = " + evalCycleEnd);
        logger.info(logTxt + "createTimeBegin = " + createTimeBegin);
        logger.info(logTxt + "createTimeEnd = " + createTimeEnd);
        logger.info(logTxt + "onsetTimeBegin = " + onsetTimeBegin);
        logger.info(logTxt + "onsetTimeEnd = " + onsetTimeEnd);
        logger.info(logTxt + "callStartTime = " + callStartTime);
        logger.info(logTxt + "callEndTime = " + callEndTime);
        logger.info(logTxt + "provinceCode = " + provinceCodes);
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "workType = " + workType);
        logger.info(logTxt + "proStatus = " + proStatus);
        logger.info(logTxt + "createUserId = " + createUserId);
        logger.info(logTxt + "modelId = " + modelIds);
        Map<String,Object> map = new HashMap<>();
        if (!Strings.isNullOrEmpty(evalCycleStart)) {
            map.put("evalCycleStart", evalCycleStart);
        }
        if (!Strings.isNullOrEmpty(evalCycleEnd)) {
            map.put("evalCycleEnd", evalCycleEnd);
        }
        if (!Strings.isNullOrEmpty(scoreFlag)) {
            map.put("scoreFlag", scoreFlag);
        }
        if (!Strings.isNullOrEmpty(createTimeBegin)) {
            map.put("createTimeBegin", DateFormatUtil.stringToDate(createTimeBegin, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        }
        if (!Strings.isNullOrEmpty(createTimeEnd)) {
            map.put("createTimeEnd", DateFormatUtil.stringToDate(createTimeEnd, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        }
        if (!Strings.isNullOrEmpty(onsetTimeBegin)) {
            map.put("onsetTimeBegin", DateFormatUtil.stringToDate(onsetTimeBegin, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        }
        if (!Strings.isNullOrEmpty(onsetTimeEnd)) {
            map.put("onsetTimeEnd", DateFormatUtil.stringToDate(onsetTimeEnd, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        }
        if (!Strings.isNullOrEmpty(callStartTime)) {
            map.put("callStartTime", DateFormatUtil.stringToDate(callStartTime, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        }
        if (!Strings.isNullOrEmpty(callEndTime)) {
            map.put("callEndTime", DateFormatUtil.stringToDate(callEndTime, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        }
        if (!Strings.isNullOrEmpty(provinceCodes)) {
            map.put("provinceCode", Arrays.asList(provinceCodes.split(",")));
        }
        if (!Strings.isNullOrEmpty(workId)) {
            map.put("workId", workId);
        }
        if (!Strings.isNullOrEmpty(workType)) {
            map.put("workType", workType);
        }
        if (!Strings.isNullOrEmpty(proStatus)) {
            map.put("proStatus", Arrays.asList(proStatus.split(",")));
        }
        if (!Strings.isNullOrEmpty(modelIds)) {
            map.put("modelId", Arrays.asList(modelIds.split(",")));
        }
        if (Strings.isNullOrEmpty(createUserId)) {
            Session session = SecurityUtils.getSubject().getSession();
            int userIdentity = (Integer) session.getAttribute("userIdentity");
            if (BaseEntity.USERIDENTITY_ZJ == userIdentity) {//质检员,看到组员包括自己创建的数据
                User user = (User) session.getAttribute(Constants.SESSION_USER_INFO);
                map.put("createUserId", userService.selectMemberIdByLeaderId(user.getId()));
            }
        } else {
            map.put("createUserId", Arrays.asList(createUserId.split(",")));
        }
        String orderBy = "lastUpdateTime desc";
        if (!Strings.isNullOrEmpty(sortName)) {
            orderBy = sortName + " " + sortOrder;
        }
        map.put("orderBy", orderBy);
        return map;
    }

    @RequestMapping(value = "/export-per-task-data", method = RequestMethod.POST)
    public void exportPerTaskData(HttpServletRequest request, HttpServletResponse response) {
        String logTxt = "【专项质检任务-导出】";
        logger.info(logTxt);
        try {
            Map<String,Object> map = getDataQuery(request, logTxt);
            List<Map<String, Object>> works = busWorkService.selectWorkInfos(map);
            logger.info("获取数据条数为：" + works.size());
            //生成excel
            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文档对象
            HSSFSheet sheet = workbook.createSheet();//创建一个工作薄对象
            //设置标题和列名称
            String[] header = {"编号", "省份", "专项质检任务名称", "创建人", "状态",
                    "通话时间段", "启动时间", "最后更新时间", "备注"};
            String title = "专项质检任务信息表";
            XlsUtil.setTableTitleHeader(workbook, sheet, Arrays.asList(header), title);
            //获取表文样式
            HSSFCellStyle tableStyle = XlsUtil.getTableStyle(workbook);
            HSSFRow row2;
            HSSFCell cell2;
            for (int j = 0; j < works.size(); j++) {
                Map source = works.get(j);
                row2 = sheet.createRow(3 + j);
                for (int i = 0; i < header.length; i++) {
                    cell2 = row2.createCell(i);
                    cell2.setCellStyle(tableStyle);
                    switch (i) {
                        case 0:
                            cell2.setCellValue(new HSSFRichTextString(j + ""));
                            break;
                        case 1:
                            cell2.setCellValue(new HSSFRichTextString(areaService.selectByPrimaryCode(source.get("provinceCode").toString()).getArea()));
                            break;
                        case 2:
                            cell2.setCellValue(new HSSFRichTextString(source.get("workName").toString()));
                            break;
                        case 3:
                            cell2.setCellValue(new HSSFRichTextString(source.get("createusername").toString()));
                            break;
                        case 4:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeTaskStatus(Integer.parseInt(source.get("proStatus").toString()))));
                            break;
                        case 5:
                            cell2.setCellValue(new HSSFRichTextString(
                                    DateFormatUtil.dateToString((Date) source.get("callStartTime"), DateFormatUtil.yyyy_MM_dd_HH_mm_ss)
                                    + "-" +
                                    DateFormatUtil.dateToString((Date) source.get("callEndTime"), DateFormatUtil.yyyy_MM_dd_HH_mm_ss)
                            ));
                            break;
                        case 6:
                            cell2.setCellValue(new HSSFRichTextString(DateFormatUtil.dateToString((Date) source.get("onsetTime"), DateFormatUtil.yyyy_MM_dd_HH_mm_ss)));
                            break;
                        case 7:
                            cell2.setCellValue(new HSSFRichTextString(DateFormatUtil.dateToString((Date) source.get("lastUpdateTime"), DateFormatUtil.yyyy_MM_dd_HH_mm_ss)));
                            break;
                        case 8:
                            cell2.setCellValue(new HSSFRichTextString(source.get("description").toString()));
                            break;
                    }
                }
            }
            for (int i = 0; i < header.length; i++) {
                sheet.autoSizeColumn((short) i, true);//自动调整列宽
            }
            String fileName = title + "_" + DateFormatUtil.getNowTime() + ".xls";
            // 清空response
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));  //转码之后下载的文件名不会出现中文乱码
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            logger.info(logTxt + "异常");
        }
    }

    @RequestMapping(value = "/export-auto-task-data", method = RequestMethod.POST)
    public void exportAutoTaskData(HttpServletRequest request, HttpServletResponse response) {
        String logTxt = "【自动质检任务-导出】";
        logger.info(logTxt);
        try {
            Map<String,Object> map = getDataQuery(request, logTxt);
            List<Map<String, Object>> works = busWorkService.selectWorkInfos(map);
            logger.info("获取数据条数为：" + works.size());
            //生成excel
            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文档对象
            HSSFSheet sheet = workbook.createSheet();//创建一个工作薄对象
            //设置标题和列名称
            String[] header = {"编号", "省份", "考核周期", "考核时间", "有效期", "自动质检任务名称",
                    "状态", "创建人", "创建时间", "启动时间", "最后更新时间", "备注"};
            String title = "自动质检任务信息表";
            XlsUtil.setTableTitleHeader(workbook, sheet, Arrays.asList(header), title);
            //获取表文样式
            HSSFCellStyle tableStyle = XlsUtil.getTableStyle(workbook);
            HSSFRow row2;
            HSSFCell cell2;
            for (int j = 0; j < works.size(); j++) {
                Map source = works.get(j);
                row2 = sheet.createRow(3 + j);
                for (int i = 0; i < header.length; i++) {
                    cell2 = row2.createCell(i);
                    cell2.setCellStyle(tableStyle);
                    switch (i) {
                        case 0:
                            cell2.setCellValue(new HSSFRichTextString(j + ""));
                            break;
                        case 1:
                            cell2.setCellValue(new HSSFRichTextString(areaService.selectByPrimaryCode(source.get("provinceCode").toString()).getArea()));
                            break;
                        case 2:
                            cell2.setCellValue(new HSSFRichTextString(source.get("evalCycleStart").toString() + "-" + source.get("evalCycleEnd").toString()));
                            break;
                        case 3:
                            cell2.setCellValue(new HSSFRichTextString(source.get("evalTimeStart").toString() + "-" + source.get("evalTimeEnd").toString()));
                            break;
                        case 4:
                            cell2.setCellValue(new HSSFRichTextString(
                                    DateFormatUtil.dateToString((Date) source.get("callStartTime"), DateFormatUtil.yyyy_MM_dd)
                                    + "-" +
                                    DateFormatUtil.dateToString((Date) source.get("callEndTime"), DateFormatUtil.yyyy_MM_dd)
                            ));
                            break;
                        case 5:
                            cell2.setCellValue(new HSSFRichTextString(source.get("workName").toString()));
                            break;
                        case 6:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeTaskStatus(Integer.parseInt(source.get("proStatus").toString()))));
                            break;
                        case 7:
                            cell2.setCellValue(new HSSFRichTextString(source.get("createusername").toString()));
                            break;
                        case 8:
                            cell2.setCellValue(new HSSFRichTextString(DateFormatUtil.dateToString((Date) source.get("createTime"), DateFormatUtil.yyyy_MM_dd_HH_mm_ss)));
                            break;
                        case 9:
                            cell2.setCellValue(new HSSFRichTextString(DateFormatUtil.dateToString((Date) source.get("onsetTime"), DateFormatUtil.yyyy_MM_dd_HH_mm_ss)));
                            break;
                        case 10:
                            cell2.setCellValue(new HSSFRichTextString(DateFormatUtil.dateToString((Date) source.get("lastUpdateTime"), DateFormatUtil.yyyy_MM_dd_HH_mm_ss)));
                            break;
                        case 11:
                            cell2.setCellValue(new HSSFRichTextString(source.get("description").toString()));
                            break;
                    }
                }
            }
            for (int i = 0; i < header.length; i++) {
                sheet.autoSizeColumn((short) i, true);//自动调整列宽
            }
            String fileName = title + "_" + DateFormatUtil.getNowTime() + ".xls";
            // 清空response
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));  //转码之后下载的文件名不会出现中文乱码
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            logger.info(logTxt + "异常");
        }
    }

    @RequestMapping(value = "/add-data", method = RequestMethod.POST)
    public HtmlResult addPerTask(HttpServletRequest request) {
        String logTxt = "【添加质检任务】";
        logger.info(logTxt);
        String provinceCode = request.getParameter("provinceCode");//省份
        String workType = request.getParameter("workType");//任务分类
        String workName = request.getParameter("workName");//质检任务名称
        String scoreFlag = request.getParameter("scoreFlag");//质检任务名称
        String evalCycleStart = request.getParameter("evalCycleStart");//考核周期开始
        String evalCycleEnd = request.getParameter("evalCycleEnd");//考核周期截止
        String evalTimeStart = request.getParameter("evalTimeStart");//考核
        String evalTimeEnd = request.getParameter("evalTimeEnd");//考核
        String onHook = request.getParameter("onHook");//挂机方
        String satisfaction = request.getParameter("satisfaction");//满意度
        String reCallFlag = request.getParameter("reCallFlag");//是否重复来电
        String minDuration = request.getParameter("minDuration");//语音最短时长
        String maxDuration = request.getParameter("maxDuration");//语音最长时长
        String description = request.getParameter("description");//任务描述
        String callStartTime = request.getParameter("callStartTime");//通话开始时间
        String callEndTime = request.getParameter("callEndTime");//通话结束时间
        String seatGroupId = request.getParameter("seatGroupId");//被质检班组
        String seatIds = request.getParameter("seatIds");//被质检座席工号
        String customerlocs = request.getParameter("customerloc");//归属地
        String customerNum = request.getParameter("customerNum");//客户号码
        String customerLevels = request.getParameter("customerLevels");//客户星级
        String customerSign = request.getParameter("customerSign");//重点客户
        String callDirection = request.getParameter("callDirection");//呼叫类型
        String callTags = request.getParameter("callTags");//话务小结
        String sysTags = request.getParameter("sysTags");//系统标签
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String modelIds = request.getParameter("modelIds");//模型ID
        logger.info(logTxt + "provinceCode = " + provinceCode);
        logger.info(logTxt + "workType = " + workType);
        logger.info(logTxt + "workName = " + workName);
        logger.info(logTxt + "scoreFlag = " + scoreFlag);
        logger.info(logTxt + "evalCycleStart = " + evalCycleStart);
        logger.info(logTxt + "evalCycleEnd = " + evalCycleEnd);
        logger.info(logTxt + "evalTimeStart = " + evalTimeStart);
        logger.info(logTxt + "evalTimeEnd = " + evalTimeEnd);
        logger.info(logTxt + "onHook = " + onHook);
        logger.info(logTxt + "satisfaction = " + satisfaction);
        logger.info(logTxt + "reCallFlag = " + reCallFlag);
        logger.info(logTxt + "minDuration = " + minDuration);
        logger.info(logTxt + "maxDuration = " + maxDuration);
        logger.info(logTxt + "description = " + description);
        logger.info(logTxt + "callStartTime = " + callStartTime);
        logger.info(logTxt + "callEndTime = " + callEndTime);
        logger.info(logTxt + "seatGroupId = " + seatGroupId);
        logger.info(logTxt + "seatIds = " + seatIds);
        logger.info(logTxt + "customerloc = " + customerlocs);
        logger.info(logTxt + "customerNum = " + customerNum);
        logger.info(logTxt + "customerLevels = " + customerLevels);
        logger.info(logTxt + "customerSign = " + customerSign);
        logger.info(logTxt + "callDirection = " + callDirection);
        logger.info(logTxt + "callTags = " + callTags);
        logger.info(logTxt + "sysTags = " + sysTags);
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "modelIds = " + modelIds);
        return busWorkService.insertSelective(request);
    }

    @RequestMapping(value = "/update-data", method = RequestMethod.POST)
    public HtmlResult updateTask(HttpServletRequest request) {
        String logTxt = "【修改质检任务】";
        logger.info(logTxt);
        String id = request.getParameter("id");//任务id
        String provinceCode = request.getParameter("provinceCode");//任务id
        String workType = request.getParameter("workType");//任务id
        String workName = request.getParameter("workName");//任务id
        String scoreFlag = request.getParameter("scoreFlag");//任务id
        String minDuration = request.getParameter("minDuration");//语音最短时长
        String maxDuration = request.getParameter("maxDuration");//语音最长时长
        String evalCycleStart = request.getParameter("evalCycleStart");//任务id
        String evalCycleEnd = request.getParameter("evalCycleEnd");//任务id
        String evalTimeStart = request.getParameter("evalTimeStart");//考核
        String evalTimeEnd = request.getParameter("evalTimeEnd");//考核
        String onHook = request.getParameter("onHook");//挂机方
        String satisfaction = request.getParameter("satisfaction");//满意度
        String reCallFlag = request.getParameter("reCallFlag");//是否重复来电
        String description = request.getParameter("description");//任务id
        String callStartTime = request.getParameter("callStartTime");//任务id
        String callEndTime = request.getParameter("callEndTime");//任务id
        String seatGroupId = request.getParameter("seatGroupId");//任务id
        String seatIds = request.getParameter("seatIds");//任务id
        String customerlocs = request.getParameter("customerloc");//归属地
        String customerNum = request.getParameter("customerNum");//任务id
        String customerLevels = request.getParameter("customerLevels");//任务id
        String customerSign = request.getParameter("customerSign");//重点客户
        String callDirection = request.getParameter("callDirection");//呼叫类型
        String callTags = request.getParameter("callTags");//话务小结
        String sysTags = request.getParameter("sysTags");//系统标签
        String serialNumber = request.getParameter("serialNumber");//任务id
        String modelIds = request.getParameter("modelIds");//任务id
        logger.info(logTxt + "id = " + id);
        logger.info(logTxt + "provinceCode = " + provinceCode);
        logger.info(logTxt + "workType = " + workType);
        logger.info(logTxt + "workName = " + workName);
        logger.info(logTxt + "scoreFlag = " + scoreFlag);
        logger.info(logTxt + "minDuration = " + minDuration);
        logger.info(logTxt + "maxDuration = " + maxDuration);
        logger.info(logTxt + "evalCycleStart = " + evalCycleStart);
        logger.info(logTxt + "evalCycleEnd = " + evalCycleEnd);
        logger.info(logTxt + "evalTimeStart = " + evalTimeStart);
        logger.info(logTxt + "evalTimeEnd = " + evalTimeEnd);
        logger.info(logTxt + "onHook = " + onHook);
        logger.info(logTxt + "satisfaction = " + satisfaction);
        logger.info(logTxt + "reCallFlag = " + reCallFlag);
        logger.info(logTxt + "description = " + description);
        logger.info(logTxt + "callStartTime = " + callStartTime);
        logger.info(logTxt + "callEndTime = " + callEndTime);
        logger.info(logTxt + "seatGroupId = " + seatGroupId);
        logger.info(logTxt + "seatIds = " + seatIds);
        logger.info(logTxt + "customerloc = " + customerlocs);
        logger.info(logTxt + "customerNum = " + customerNum);
        logger.info(logTxt + "customerLevels = " + customerLevels);
        logger.info(logTxt + "customerSign = " + customerSign);
        logger.info(logTxt + "callDirection = " + callDirection);
        logger.info(logTxt + "callTags = " + callTags);
        logger.info(logTxt + "sysTags = " + sysTags);
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "modelIds = " + modelIds);
        return busWorkService.updateByPrimaryKeySelective(request);
    }

    @RequestMapping(value = "/del-data-by-id", method = RequestMethod.POST)
    public HtmlResult delPerTask(HttpServletRequest request) {
        String logTxt = "【删除质检任务】";
        logger.info(logTxt);
        String ids = request.getParameter("ids");//任务ids
        logger.info(logTxt + "ids = " + ids);
        return busWorkService.deleteByPrimaryKey(ids);
    }

    @RequestMapping(value = "/start-or-stop-task", method = RequestMethod.POST)
    public HtmlResult startTask(HttpServletRequest request) {
        String logTxt = "【启动质检任务】";
        logger.info(logTxt);
        String workIds = request.getParameter("id");//任务ids
        String startOrStop = request.getParameter("startOrStop");//启动/停止
        logger.info(logTxt + "workIds = " + workIds);
        logger.info(logTxt + "startOrStop = " + startOrStop);
        try {
            return busWorkService.startTask(request);
        } catch (IOException e) {
            e.printStackTrace();
            return HtmlResult.failure("1".equals(startOrStop) ? "启动" : "停止" +"失败");
        }
    }

    @RequestMapping(value = "/get-tasks", method = RequestMethod.POST)
    public HtmlResult getTaskList(HttpServletRequest request) throws UnknownHostException {
        String logTxt = "【获取全部任务信息列表】";
        logger.info(logTxt);
        String code = request.getParameter("code");//code
        logger.info(logTxt + "code = " + code);
        BusWorkExample example = new BusWorkExample();
        BusWorkExample.Criteria criteria = example.createCriteria();
        Session session = SecurityUtils.getSubject().getSession();
        SysArea area = (SysArea) session.getAttribute("areaInfo");
        if (area != null) {
            criteria.andProvincecodeEqualTo(area.getCode());
        }
        if (!Strings.isNullOrEmpty(code)) {
            criteria.andProvincecodeEqualTo(code);
        }
        criteria.andProstatusGreaterThanOrEqualTo(BaseEntity.TASK_PROSTATUS_START);
        example.setOrderByClause("lastUpdateTime desc");


        List<BusWorkWithBLOBs> works = busWorkService.selectByExample(example);

        List<BusWorkWithBLOBs> workList = works;
        int userIdentity = (Integer) session.getAttribute("userIdentity");
        if (BaseEntity.USERIDENTITY_ZX == userIdentity) {
            workList = new ArrayList<>();
            workList = esUtil.taskListQ(workList, works);
        }

        return HtmlResult.success(workList);
    }

    @RequestMapping(value = "/get-task-by-id", method = RequestMethod.POST)
    public HtmlResult getTaskNameById(HttpServletRequest request) {
        String logTxt = "【根据id获取任务】";
        logger.info(logTxt);
        if (Strings.isNullOrEmpty(request.getParameter("id"))) {
            return HtmlResult.failure("任务id为空");
        }
        Long id = Long.parseLong(request.getParameter("id"));//任务id
        logger.info(logTxt + "id = " + id);
        return HtmlResult.success(busWorkService.selectByPrimaryKey(id));
    }

    @RequestMapping(value = "/get-tasks-by-type", method = RequestMethod.POST)
    public HtmlResult getTaskByType(HttpServletRequest request) {
        String logTxt = "【根据workType获取任务】";
        logger.info(logTxt);
        Integer workType = Integer.parseInt(request.getParameter("workType"));//任务id
        String code = request.getParameter("code");//code
        logger.info(logTxt + "workType = " + workType);
        logger.info(logTxt + "code = " + code);
        Session session = SecurityUtils.getSubject().getSession();
        SysArea area = (SysArea) session.getAttribute("areaInfo");
        BusWorkExample example = new BusWorkExample();
        BusWorkExample.Criteria criteria = example.createCriteria();
        criteria.andWorktypeEqualTo(workType);
        if (!Strings.isNullOrEmpty(code)) {
            criteria.andProvincecodeEqualTo(code);
        }
        if (area != null) {
            criteria.andProvincecodeEqualTo(area.getCode());
        }
        int userIdentity = (Integer) session.getAttribute("userIdentity");
        if (BaseEntity.USERIDENTITY_ZJ == userIdentity) {//质检员,看到组员包括自己创建的数据
            User user = (User) session.getAttribute(Constants.SESSION_USER_INFO);
            criteria.andCreateuseridIn(userService.selectMemberIdByLeaderId(user.getId()));
        }
        example.setOrderByClause("lastUpdateTime desc");
        return HtmlResult.success(busWorkService.selectByExample(example));
    }

    @RequestMapping(value = "/get-tasks-by-pro", method = RequestMethod.POST)
    public HtmlResult getTaskByPro(@RequestParam(value = "proCode") final String proCode) {
        String logTxt = "【根据省份code获取任务】";
        logger.info(logTxt);
        logger.info(logTxt + "proCode = " + proCode);
        BusWorkExample example = new BusWorkExample();
        example.createCriteria().andProvincecodeEqualTo(proCode);
        return HtmlResult.success(busWorkService.selectByExample(example));
    }

    @RequestMapping(value = "/get-modelId-by-taskId", method = RequestMethod.POST)
    public HtmlResult getModelByTaskId(HttpServletRequest request) {
        String logTxt = "【根据id获取任务模型关系表】";
        logger.info(logTxt);
        Long id = Long.parseLong(request.getParameter("id"));//任务id
        logger.info(logTxt + "id = " + id);
        BusWorkModelExample example = new BusWorkModelExample();
        example.createCriteria().andWorkidEqualTo(id);
        return HtmlResult.success(busWorkModelService.findModel(example));
    }

    @RequestMapping(value = "/get-task-by-modelId", method = RequestMethod.POST)
    public HtmlResult getTaskByModelId(HttpServletRequest request) {
        String logTxt = "【根据模型id获取任务】";
        logger.info(logTxt);
        Long modelId = Long.parseLong(request.getParameter("modelId"));//模型id
        logger.info(logTxt + "modelId = " + modelId);
        return HtmlResult.success(busWorkService.getTaskByModelId(modelId));
    }

    @RequestMapping(value = "/get-task-expir-date-by-del", method = RequestMethod.POST)
    public HtmlResult getTaskExpiryDateByDelete(HttpServletRequest request) {
        String logTxt = "【获取任务删除的有效期】";
        logger.info(logTxt);
        String ids = request.getParameter("id");//任务id
        String modelName = request.getParameter("modelName");
        String workName = request.getParameter("workName");
        logger.info(logTxt + "ids = " + ids);
        logger.info(logTxt + "modelName = " + modelName);
        logger.info(logTxt + "workName = " + workName);
        return busWorkService.getTaskExpiryDateByDelete(request);
    }

    @RequestMapping(value = "/work-uniqueness", method = RequestMethod.POST)
    public HtmlResult workUniqueness(HttpServletRequest request) {
        String logTxt = "【任务名称唯一性验证】";
        logger.info(logTxt);
        String id = request.getParameter("id");//任务id
        String workName = request.getParameter("workName");//任务name
        int workType = Integer.parseInt(request.getParameter("workType"));//任务类型
        logger.info(logTxt + "id = " + id);
        logger.info(logTxt + "workName = " + workName);
        logger.info(logTxt + "workType = " + workType);
        BusWorkExample example = new BusWorkExample();
        example.createCriteria().andWorknameEqualTo(workName).andWorktypeEqualTo(workType);
        List<BusWorkWithBLOBs> works = busWorkService.selectByExample(example);
        if (!works.isEmpty()) {
            if (!Strings.isNullOrEmpty(id)) {
                BusWorkExample example1 = new BusWorkExample();
                example1.createCriteria().andWorknameEqualTo(workName).andWorktypeEqualTo(workType).andIdEqualTo(Long.parseLong(id));
                List<BusWorkWithBLOBs> busWorks = busWorkService.selectByExample(example1);
                if (!busWorks.isEmpty()) {
                    return HtmlResult.success();
                }
            }
            return HtmlResult.failure("任务名称已存在");
        }
        return HtmlResult.success();
    }
}
